const Navigation = require('../models/navigation.model.js')
const util = require('../util/util.js')
const responseResultData = util.responseResultData
// 创建新的权限对象
exports.create = (req, res) => {
  // 验证请求
  if (!req.body) {
    responseResultData(res, 200, false,  '参数不能为空', '')
    return
  }
  // 创建新的对象
  const navigationModel = Navigation.createNew({
    name: req.body.name ?? '',
    parentId: req.body.parentId ?? 0,
    type: req.body.type ?? 0,
    controller: req.body.controller ?? '',
    action: req.body.action ?? '',
    icon: req.body.icon ?? '',
    authorize: req.body.authorize ?? '',
    summary: req.body.summary ?? '',
    sort: req.body.sort ?? 255
  })
  Navigation.create( [navigationModel], (err, data) => {
    if (err) {
      responseResultData(res, 200, false,  err.message || '创建权限错误', '')
      return
    }
    responseResultData(res, 200, true, '', '')
  })
  
}
// 根据ID查询权限
exports.getDetail = (req, res) => {
  // 验证请求
  if (!req.query || !req.query.id) {
    responseResultData(res, 200, false,  '参数不能为空', '')
    return
  }

  // 查找
  Navigation.getById(req.query.id, (err, data) => {
    if (err) {
      responseResultData(res, 200, false,  err.message || '查找权限错误', '')
      return
    }
    if(!data) {
      responseResultData(res, 200, false, '未找到权限信息')
      return
    }
    responseResultData(res, 200, true, '', data)
  })
}
// 获取权限列表
exports.getList = (req, res) => {
  // 查找所有
  Navigation.getList((err, data) => {
    if (err) {
      responseResultData(res, 200, false,  err.message || '获取权限列表错误', '')
      return
    }
    // 格式化数据
    responseResultData(res, 200, true, '', data)
  })
}

// 根据ID更新权限
exports.update = (req, res) => {
  // 验证请求
  if (!req.body) {
    responseResultData(res, 200, false,  '参数不能为空', '')
    return
  }
  const body = {
    id: req.body.id,
    name: req.body.name ?? '',
    parentId: req.body.parentId ?? 0,
    type: req.body.type ?? 0,
    controller: req.body.controller ?? '',
    action: req.body.action ?? '',
    icon: req.body.icon ?? '',
    authorize: req.body.authorize ?? '',
    summary: req.body.summary ?? '',
    sort: req.body.sort ?? 255
  }
  // 更新
  Navigation.updateById(body, (err, data) => {
    if (err) {
      responseResultData(res, 200, false,  err.message || '更新权限错误', '')
      return
    }
    responseResultData(res, 200, true, '', data)
  })

}
// 删除权限
exports.delete = (req, res) => {
  // 验证请求
  if (!req.body || !req.body.id) {
    responseResultData(res, 200, false,  '参数不能为空', '')
    return
  }
  // 删除
  Navigation.delete(req.body.id, (err) => {
    if (err) {
      responseResultData(res, 200, false,  err.message || '删除权限错误', '')
      return
    }
    responseResultData(res, 200, true, '', '')
  })
}
// 设置权限
exports.setNavigation = (req, res) => {
  // 验证请求
  if (!req.body) {
    responseResultData(res, 200, false,  '参数不能为空', '')
    return
  }
  
}

